package demo.socket;

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpLiaoTian {

    public static void main(String[] args) throws SocketException {
        DatagramSocket ds = new DatagramSocket();
        Frame f = new Frame("����");
        TextArea sendTa = new TextArea(3, 50);
        TextArea receTa = new TextArea(20, 50);
        sendTa.addKeyListener(new KeyAdapter() {
            boolean isSend = true;

            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    sendTa.setText("");
                    isSend = true;
                }
            }

            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER && isSend)
                    try {
                        byte[] data = sendTa.getText().getBytes();
                        ds.send(new DatagramPacket(data, data.length, InetAddress.getByName("127.0.0.1"), 10000));
                        isSend = false;
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
            }

        });
        f.setLayout(new FlowLayout());
        f.setBounds(600, 500, 400, 500);
        f.add(receTa);
        f.add(sendTa);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                ds.close();
                System.exit(0);
            }
        });
        f.setVisible(true);
        new Thread() {
            @SuppressWarnings("resource")
            public void run() {
                DatagramSocket dsa = null;
                try {
                    dsa = new DatagramSocket(10000);
                } catch (SocketException e1) {
                    e1.printStackTrace();
                }
                while (true) {
                    byte[] b = new byte[1024];
                    DatagramPacket dp = new DatagramPacket(b, b.length);
                    try {
                        dsa.receive(dp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    receTa.append(dp.getAddress() + "����" + dp.getPort() + "����"
                            + new String(dp.getData(), 0, dp.getLength()) + "\n");
                }
            }
        }.start();
    }

}
